package zero.springdemo.springquartzdemo.core.quartz

import org.quartz.Scheduler
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.scheduling.annotation.EnableScheduling
import org.springframework.scheduling.quartz.SchedulerFactoryBean
import org.springframework.core.io.ClassPathResource
import org.springframework.beans.factory.config.PropertiesFactoryBean
import java.io.IOException
import java.util.*


@Configuration
@EnableScheduling
open class QuartScheduler {


    @Autowired
    private lateinit var myJobFactory: MyJobFactory

    @Bean(name = ["MySchedulerFactory"])
    open fun schedulerFactoryBean(): SchedulerFactoryBean {
        val factory = SchedulerFactoryBean();

        factory.setOverwriteExistingJobs(true)

        // 延时启动
        factory.setStartupDelay(20)

        // 加载quartz数据源配置
        factory.setQuartzProperties(quartzProperties())

        // 自定义Job Factory，用于Spring注入
        factory.setJobFactory(myJobFactory);

        return factory
    }

    /**
     * 默认的定时器
     */
    @Bean("defaultScheduler")
    open fun getScheduler(@Qualifier("MySchedulerFactory") factory: SchedulerFactoryBean?): Scheduler? {
        if (factory !== null) {
            val scheduler = factory.scheduler

            return scheduler
        }
        return null
    }

    /**
     * 加载quartz数据源配置
     *
     * @return
     * @throws IOException
     */
    @Bean
    @Throws(IOException::class)
    open fun quartzProperties(): Properties {
        val propertiesFactoryBean = PropertiesFactoryBean()
        propertiesFactoryBean.setLocation(ClassPathResource("config/quartz.properties"))
        propertiesFactoryBean.afterPropertiesSet()
        return propertiesFactoryBean.getObject()
    }
}
